package com.sunjob.mrotech.server.Impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.domain.loginServer.SysUser;
import com.sunjob.common.domain.tech.*;
import com.sunjob.common.result.Result;
import com.sunjob.common.util.MROUtils;
import com.sunjob.mrotech.mapper.ShapeMapper;
import com.sunjob.mrotech.server.ShapeServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.sunjob.common.constant.MROConstant.TECH;

/**
 * @author : xiaozhoutongxue
 * @date : 2022/8/2 9:48
 */
@Service
@Slf4j
public class ShapeServerImpl implements ShapeServer {
    @Autowired
    ShapeMapper shapeMapper;
    @Autowired
    RedisTemplate redisTemplate;

    public String getUserName() {
        SaSession tokenSession = StpUtil.getTokenSession();
        SysUser sysUser = (SysUser) tokenSession.get("userInfo");
        return sysUser.getUserName();
    }

    @Override
    @Transactional
    public Result insertShapeComposition(InsertShapeCompositionVO ins) {
        if (ins.getComposition().size() == 0) {
            // todo 创建返回码常量
            return Result.build(null, 250, "请选择至少一个二级结构");
        }
        LocalDateTime now = LocalDateTime.now();
        Long shapeId = MROUtils.nextId();
        //增加一级构型
        int flag = shapeMapper.insertShape(shapeId, ins.getShapeName(), getUserName(), now);
        if (flag > 0) {
            log.info("insert Shape successful:id:{}", shapeId);
        } else {
            return Result.fail("数据错误");
        }

        //刷入构型数据
        List<InsertShapeCompositionVO.Trans2Ids> composition = ins.getComposition();
        for (int i = 0; i < composition.size(); i++) {
            List<Long> trans3Ids = composition.get(i).getTrans3Ids();
            Long shape2Id = composition.get(i).getTran2Id();
            //增加主二中间表
            shapeMapper.insertShapeAndShape2(shapeId, shape2Id, getUserName(), now);
            for (int j = 0; j < trans3Ids.size(); j++) {
                //增加实例表
                shapeMapper.insertShapeComposition(shapeId, shape2Id, trans3Ids.get(j), getUserName(), now);
            }
        }
        log.info("insert ShapeComposition successful");
        return Result.ok(null, "构型增加成功");
    }

    @Override
    public Boolean insertShape2(TransShape2 com) {
        if (com.getShape2Id() == 0) {
            com.setShape2Id(MROUtils.nextId());
        }
        LocalDateTime now = LocalDateTime.now();
        int flag = shapeMapper.insertShape2(com.getShape2Id(), com.getShape2Name(), getUserName(), now);
        return flag > 0 ? true : false;
    }

    @Override
    public Boolean insertShape3(TransShape3 com) {
        if (com.getShape3Id() == 0) {
            com.setShape3Id(MROUtils.nextId());
        }
        LocalDateTime now = LocalDateTime.now();
        int flag = shapeMapper.insertShape3(com.getShape3Id(), com.getShape3Name(), com.getShape2Id(), getUserName(), now);
        return flag > 0 ? true : false;
    }

    @Override
    public List<TransShape> getAllShape(int limit) {
        if (limit==0){
            return shapeMapper.getAllShape(1000);
        }else {
            return shapeMapper.getAllShape(limit);
        }

    }

    @Override
    public List<TransShape> getShapeByLittle(String little) {
        return shapeMapper.getShapeByLittle(little);
    }

    public TransShape getOrSetshapeCompositionInRedis(Long id) {
        String redisKey = TECH + id;
        TransShape transShapeComposition = (TransShape) redisTemplate.opsForValue().get(redisKey);
        if (transShapeComposition == null) {
            //查询数据库
            transShapeComposition = shapeMapper.getShapeCompositionById(id);
            if (transShapeComposition != null) {
                redisTemplate.opsForValue().set(redisKey, transShapeComposition, 3L, TimeUnit.MINUTES);
            }
            log.info("get from mysql");
            return transShapeComposition;
        } else {
            redisTemplate.expire(redisKey, 3, TimeUnit.MINUTES);
            log.info("get from redis");
            return transShapeComposition;
        }
    }

    @Override
    public Result getshapeCompositionById(Long id) {
        TransShape transShapeComposition = getOrSetshapeCompositionInRedis(id);
        if (transShapeComposition != null) {
            return Result.ok(transShapeComposition, "查询成功");
        } else {
            return Result.fail("没有查询到哦");
        }
    }

    @Override
    public Result getShape2CompositionById(Long id) {
        TransShape transShapeComposition = getOrSetshapeCompositionInRedis(id);
        List<TransShape2> transShape2s = transShapeComposition.getTransShape2s();
        if (transShape2s != null) {
            return Result.ok(transShape2s, "查询成功");
        } else {
            return Result.fail("没有查询到哦");
        }
    }

    @Override
    public Result getShapa3CompositionByShapeIdAndShape2Id(Long shapeId, Long shape2Id) {
        TransShape transShapeComposition = getOrSetshapeCompositionInRedis(shapeId);
        List<TransShape2> transShape2s = transShapeComposition.getTransShape2s();
        for (TransShape2 transShape2 : transShape2s) {
            if (transShape2.getShape2Id().equals(shape2Id)) {
                return Result.ok(transShape2.getTransShape3s(), "查询成功");
            }
        }
        return Result.fail("没有查询到哦");

    }

    @Override
    public Result getAllShapa2Composition() {
        List<TransShape2> allShapa2Composition = shapeMapper.getAllShapa2Composition();
        return Result.ok(allShapa2Composition, "查询成功");
    }

    @Override
    public Result getAllShapa3Composition(Long shape2Id) {
        List<TransShape3> allShapa3Composition = shapeMapper.getAllShapa3Composition(shape2Id);
        return Result.ok(allShapa3Composition, "查询成功");
    }

    @Override
    @Transactional
    public Result deleteShapeById(Long id) {
        int i = shapeMapper.deleteShapeById(id, getUserName(), LocalDateTime.now());
        String redisKey = TECH + id;
        redisTemplate.delete(redisKey);
        log.info("delete cache successful");
        if (i > 0) {
            return Result.ok(null, "删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    @Override
    public Result upadateShape3Composition(Long shapeId, Long shape2Id, Long shape3Id, int isNew) {
        LocalDateTime now = LocalDateTime.now();
        String redisKey = TECH + shapeId;
        redisTemplate.delete(redisKey);
        log.info("delete cache successful");
        int flag;
        //新增一条
        if (isNew == 1) {
            flag = shapeMapper.insertShapeComposition(shapeId, shape2Id, shape3Id, getUserName(), now);
        } else {
            //删除一条
            flag = shapeMapper.upadateShape3Composition(shapeId, shape2Id, shape3Id);
        }
        // todo 重载页面
        return flag > 0 ? Result.ok(null, "更新成功") : Result.fail("更新失败");
    }


}
